<template>
  <view class="index-container">
    <!-- 顶部定位和搜索 -->
    <view class="header">
      <view class="header-top">
        <view class="location">
          <uni-icons type="location" size="16" color="#fff"></uni-icons>
          <text>杭州市梦想小镇</text>
        </view>
        <uni-icons type="notification" size="20" color="#fff"></uni-icons>
      </view>
      <view class="search-box">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <input type="text" placeholder="永辉超市优惠商品" v-model="searchKeyword" @confirm="handleSearch" />
      </view>
    </view>
    <!-- 广告 -->
    <view class="banner">
      <image src="/static/imgs/assets/02.jpg" mode="scaleToFill"></image>
    </view>

    <!-- 分类导航 -->
    <view class="category-grid">
      <view class="category-item" v-for="(item, index) in categories" :key="index">
        <image :src="item.icon" mode="aspectFit"></image>
        <text>{{item.name}}</text>
      </view>
    </view>

    <!-- 附近店铺 -->
    <view class="nearby-shops">
      <view class="section-title">
        <text>附近店铺</text>
        <text class="more" @click="goToShopList">查看更多 ></text>
      </view>
      <view class="shop-list">
        <!-- 点击事件 -->
        <view class="shop-item" v-for="(shop, index) in shops" :key="index" @click="goToShop(shop)">
          <image :src="shop.imgUrl" mode="aspectFill"></image>
          <view class="shop-info">
            <text class="shop-name">{{shop.name}}</text>
            <view class="shop-data">
              <text>月售：{{shop.sales || 0}}</text>
              <text>起送：{{shop.expressLimit || 0}}</text>
              <text>基础运费：{{shop.expressPrice || 0}}</text>
            </view>
            <text class="shop-slogan" :style="{color: shop.sloganColor || '#ff6b6b'}">{{shop.slogan || ''}}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  
  data() {
    return {
      searchKeyword: '', // 添加搜索关键词
      categories: [
        { name: '超市便利', icon: '/static/imgs/assets/super.png' },
        { name: '菜场', icon: '/static/imgs/assets/market.png' },
        { name: '水果店', icon: '/static/imgs/assets/fruits.png' },
        { name: '鲜花绿植', icon: '/static/imgs/assets/flower.png' },
        { name: '医药健康', icon: '/static/imgs/assets/drug.png' },
        { name: '家居时尚', icon: '/static/imgs/assets/home.png' },
        { name: '烘焙蛋糕', icon: '/static/imgs/assets/cake.png' },
        { name: '签到', icon: '/static/imgs/assets/sign.png' },
        { name: '大牌免运', icon: '/static/imgs/assets/prestige.png' },
        { name: '红包套餐', icon: '/static/imgs/assets/red.png' }
      ],
      shops: [] // 初始化空数组
    }
  },
  onLoad() {
    this.fetchShops()
  },
  methods: {
    async fetchShops() {
      try {
        const res = await uni.request({
          url: 'http://localhost:3000/hotList'
        });
        
        if (res.statusCode === 200) {
          console.log('获取到的店铺数据:', res.data);
          this.shops = res.data;
          
          // 确保每个店铺都有_id  ///测试
          this.shops.forEach((shop, index) => {
            if (!shop._id) {
              console.warn(`店铺 ${index} 缺少_id:`, shop);
              // 如果没有_id，使用索引作为临时id
              shop._id = `shop_${index}`;
            }
          });
        } else {
          console.error('获取店铺数据失败:', res.statusCode);
        }
      } catch (error) {
        console.error('获取店铺数据失败:', error);
      }
    },
    
    // 添加导航到店铺列表页的方法
    goToShopList() {
      uni.navigateTo({
        url: '/pages/shop/shop-list',
        fail: (err) => {
          console.error('导航失败:', err)
        }
      })
    },
    
    // 添加导航到店铺详情页的方法
    goToShop(shop) {
      console.log('点击店铺:', shop);
      
      if (!shop || !shop._id) {
        console.error('店铺数据不完整:', shop);
        uni.showToast({
          title: '店铺数据不完整',
          icon: 'none'
        });
        return;
      }
      
      // 保存店铺信息到本地存储
      uni.setStorageSync('shopInfo', JSON.stringify(shop));
      
      // 导航到店铺详情页 
      uni.navigateTo({
        url: `/pages/shop/shop-detail?id=${shop._id}&name=${encodeURIComponent(shop.name)}`,
        success: () => {
          console.log('导航到店铺成功:', shop.name);
        },
        fail: (err) => {
          console.error('导航到店铺详情页失败:', err);
          uni.showToast({
            title: '导航失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 处理搜索功能
    handleSearch() {
      if (!this.searchKeyword.trim()) {
        uni.showToast({
          title: '请输入搜索关键词',
          icon: 'none'
        });
        return;
      }
      
      console.log('搜索关键词:', this.searchKeyword);
      
      // 保存搜索关键词到本地存储
      uni.setStorageSync('searchKeyword', this.searchKeyword);
      
      // 如果有默认店铺，则在该店铺中搜索
      if (this.shops && this.shops.length > 0) {
        const defaultShop = this.shops[0];
        uni.navigateTo({
          url: `/pages/shop/shop-detail?id=${defaultShop._id}&name=${encodeURIComponent(defaultShop.name)}&keyword=${encodeURIComponent(this.searchKeyword)}`,
          success: () => {
            console.log('导航到搜索结果页成功');
            this.searchKeyword = ''; // 清空搜索框
          },
          fail: (err) => {
            console.error('导航到搜索结果页失败:', err);
            uni.showToast({
              title: '搜索失败',
              icon: 'none'
            });
          }
        });
      } else {
        // 如果没有默认店铺，则跳转到店铺列表页
        uni.navigateTo({
          url: `/pages/shop/shop-list?keyword=${encodeURIComponent(this.searchKeyword)}`,
          success: () => {
            console.log('导航到店铺列表页成功');
            this.searchKeyword = ''; // 清空搜索框
          },
          fail: (err) => {
            console.error('导航到店铺列表页失败:', err);
            uni.showToast({
              title: '搜索失败',
              icon: 'none'
            });
          }
        });
      }
    }
  }
}
</script>

<style lang="scss">
.index-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.header {
  background-color: #0086ff;
  padding: 20rpx;
  display: flex;
  align-items: center;

  .location {
    display: flex;
    align-items: center;
    color: #fff;
    font-size: 28rpx;
    margin-right: 20rpx;
    
    text {
      margin-left: 6rpx;
    }
  }

  .search-box {
    flex: 1;
    background-color: #fff;
    border-radius: 30rpx;
    display: flex;
    align-items: center;
    padding: 10rpx 20rpx;
    margin: 0 20rpx;

    input {
      flex: 1;
      font-size: 26rpx;
      margin-left: 10rpx;
      color: #333;
    }
  }
}

.banner {
  margin: 20rpx;
  border-radius: 12rpx;
  overflow: hidden;
  position: relative;
  background-color: #c7f2ff;
  height: 180rpx;

  image {
    width: 100%;
    height: 100%;
  }
}

.category-grid {
  background-color: #fff;
  padding: 20rpx;
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 20rpx;

  .category-item {
    display: flex;
    flex-direction: column;
    align-items: center;

    image {
      width: 60rpx;
      height: 60rpx;
      margin-bottom: 10rpx;
    }

    text {
      font-size: 24rpx;
      color: #333;
    }
  }
}

.nearby-shops {
  margin-top: 20rpx;
  background-color: #fff;
  padding: 20rpx;

  .section-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    
    text {
      font-size: 28rpx;
      font-weight: bold;
    }
    
    .more {
      color: #999;
      font-size: 24rpx;
      font-weight: normal;
    }
  }

  .shop-item {
    display: flex;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #eee;

    image {
      width: 120rpx;
      height: 120rpx;
      border-radius: 8rpx;
      margin-right: 20rpx;
    }

    .shop-info {
      flex: 1;

      .shop-name {
        font-size: 30rpx;
        font-weight: bold;
        margin-bottom: 10rpx;
      }

      .shop-data {
        display: flex;
        flex-wrap: wrap;
        margin-bottom: 10rpx;
        
        text {
          font-size: 24rpx;
          color: #666;
          margin-right: 20rpx;
        }
      }

      .shop-slogan {
        font-size: 24rpx;
      }
    }
  }
}
</style>
